<template>
  <div class="common-layout">
    <el-container>
      <el-header class="header-container">
        <div class="logo">
          <img src="../img/yz.webp" alt="永泽游戏网" />
          <span class="yz">欢迎使用永泽游戏网</span>
        </div>
        <div class="header-right">
          <div class="search-section">
            <el-input
              v-model="searchQuery"
              placeholder="搜索游戏"
              class="search-input"
              clearable
              @input="searchGames"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
              <template #append>
                <el-button type="primary" @click="searchGames">搜索</el-button>
              </template>
            </el-input>
          </div>
        </div>  
        <div class="header-right">
          <div class="user-info">
            <el-avatar class="avatar" :src="userInfo.imgUrl" />
            <el-dropdown placement="bottom">
              <el-button class="user-dropdown-btn">
                <span>未登录</span>
                <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-button class="dropdown-btn" @click="login">
                      <el-icon><User /></el-icon>
                      <span>查看个人信息</span>
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button class="dropdown-btn" @click="login">
                      <el-icon><Plus /></el-icon>
                      <span>上传游戏</span>
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button class="dropdown-btn" @click="login">
                      <el-icon><Star /></el-icon>
                      <span>我的喜欢</span>
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>

      <el-main>
        <!-- 公告区域 -->
        <el-card class="announcement-section">
          <div class="section-header">
            <el-icon class="section-icon"><Bell /></el-icon>
            <h2 class="section-title">网站公告</h2>
          </div>
          <el-collapse v-model="activeNames" @change="handleChange" class="custom-collapse">
            <el-collapse-item
              v-for="(announcement, index) in announcements"
              :key="index"
              :name="index"
            >
              <template #title>
                <div class="announcement-header">
                  <el-tag type="success" effect="dark" size="small">公告</el-tag>
                  <span class="announcement-title">{{ announcement.name }}</span>
                  <span class="announcement-date">{{ formatDate(announcement.createTime) }}</span>
                </div>
              </template>
              <div class="announcement-content">
                {{ announcement.content }}
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-card>

        <div class="home-container">

          <!-- 分类导航 -->
          <el-card class="category-section">
            <div class="section-header">
              <el-icon class="section-icon"><Menu /></el-icon>
              <h2 class="section-title">游戏分类</h2>
            </div>
            <div class="category-bar">
              <el-button
                type="primary"
                :class="{ 'active-category': !activeCategory }"
                @click="list()"
              >
                全部
              </el-button>
              <el-button
                v-for="category in categories"
                :key="category"
                type="primary"
                :class="{ 'active-category': activeCategory === category }"
                @click="filterGames(category)"
              >
                {{ category }}
              </el-button>
            </div>
          </el-card>

          <!-- 游戏列表 -->
          <el-card class="games-section">
            <div class="section-header">
              <el-icon class="section-icon"><Collection /></el-icon>
              <h2 class="section-title">游戏库</h2>
            </div>

            <el-empty v-if="filteredGames.length === 0" description="暂无游戏" />

            <div v-else class="game-grid">
              <GameCard
                v-for="game in filteredGames"
                :key="game.id"
                :game="game"
                @like="toggleFavorite"
                @view="viewGameDetails"
              />
            </div>

            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                :page-size="pageSize"
                layout="prev, pager, next, jumper"
                :total="totalGames"
                @current-change="handlePageChange"
                background
              />
            </div>
          </el-card>
        </div>
      </el-main>

      <el-footer class="footer">
        <div class="footer-content">
          <div class="footer-logo">
            <img src="../img/yz.webp" alt="永泽游戏网" />
            <span>永泽游戏网</span>
          </div>
          <div class="footer-links">
            <button @click="showInformation">关于我们</button>
          </div>
          <div class="footer-copyright">
            © {{ new Date().getFullYear() }} 永泽游戏网 版权所有
          </div>
        </div>
      </el-footer>
    </el-container>
    <el-dialog
                        v-model="dialogVisible"
                        title="关于我们"
                        width="500"
                        :before-close="handleClose"
                      >
<p>我们是一个非营利组织，网站的所有贡献者均为计算机行业的在校生或从业者。我们希望通过以学校为中心的形式发展学生社区、传递开源理念。我们所建设的所有网站均不会为私人牟利，即使产生了相关收益也将全部投入到社区建设当中。</p>
<p>我们无法保证社区网站能够达到商业网站的稳定性，所有网站的出发点和内容都旨在为学生提供实践锻炼的机会，同时服务于计算机行业及其他领域的终身学习者。</p>
                        <template #footer>
                          <div class="dialog-footer">
                            <el-button @click="dialogVisible = false">取消</el-button>
                          </div>
                        </template>
      </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { Bell, Search, ArrowDown, User, Star, SwitchButton, StarFilled, Menu, Collection,Plus } from '@element-plus/icons-vue';
import GameCard from '../views/GameCard.vue';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import request from '../axios/request';
import { useAuthStore } from '../stores/userStore';

const store = useAuthStore();
const router = useRouter();
const route = useRoute();

const activeNames = ref([0]);
const userInfo = ref({});
const searchQuery = ref('');
const activeCategory = ref('');
const currentPage = ref(1);
const pageSize = ref(15);
const totalGames = ref(0);
const games = ref([]);
const filteredGames = ref([]);
const announcements = ref([]);
const categories = ref([]);
const dialogVisible = ref(false);
const showInformation = () =>{
  dialogVisible.value = true
}
// 页面键
const windowId = ref(Math.random().toString(36).substr(2, 9)); // 每次新标签页生成唯一ID
const pageKey = computed(() => sessionStorage.getItem('pageKey') || `${route.path || '/gamelist'}-${windowId.value}`);
const currentUser = computed(() => store.getActiveUser(pageKey.value));

// 计算精选游戏
const featuredGames = computed(() => games.value.slice(0, 3));

const login = ()=>{
  ElMessage.info('请先登录')
  router.push('/login')
}

// 初始化函数
onMounted(async () => {
  list();
  getNotices();
});

// 获取游戏列表
const list = async () => {
  try {
    const res = await request({
      url: '/games/listPage',
      method: 'post',
      data: {
        pageSize: pageSize.value,
        pageNum: currentPage.value,
        param: { name: searchQuery.value },
      },
    });
    if (res.data.code === 200) {
      games.value = res.data.data || [];
      totalGames.value = res.data.total || 0;
      filteredGames.value = res.data.data || [];
    } else {
      ElMessage.error('获取游戏失败');
    }
  } catch (err) {
    console.error('请求失败:', err.response?.data || err);
    ElMessage.error('请求游戏列表失败');
    if (err.message === '登录已失效，请重新登录') {
      router.push('/');
    }
  }
};

// 获取公告
const getNotices = async () => {
  try {
    const res = await request({
      url: '/notice/viewNotices',
      method: 'get',
    });
    if (res.data.code === 200) {
      announcements.value = res.data.data || [];
    } else {
      ElMessage.error('获取公告失败');
    }
  } catch (err) {
    console.error('请求失败:', err.response?.data || err);
    ElMessage.error('请求公告失败');
    if (err.message === '登录已失效，请重新登录') {
      router.push('/');
    }
  }
};

// 获取分类
const getCategories = async () => {
  try {
    const res = await request({
      url: '/games/getCategories',
      method: 'get',
    });
    if (res.data.code === 200) {
      categories.value = res.data.data || [];
    } else {
      ElMessage.error('获取分类失败');
    }
  } catch (err) {
    console.error('请求失败:', err.response?.data || err);
    ElMessage.error('请求分类失败');
    if (err.message === '登录已失效，请重新登录') {
      router.push('/');
    }
  }
};

// 搜索游戏
const searchGames = async () => {
  if (searchQuery.value.trim()) {
    try {
      const res = await request({
        url: '/games/search',
        method: 'post',
        params: { keyword: searchQuery.value },
      });
      if (res.data.code === 200) {
        games.value = res.data.data || [];
        filteredGames.value = res.data.data || [];
      } else {
        ElMessage.error('搜索失败');
      }
    } catch (err) {
      console.error('搜索失败:', err.response?.data || err);
      ElMessage.error('搜索失败，请检查网络');
    }
  } else {
    await list();
  }
};

// 筛选游戏
const filterGames = async (category) => {
  try {
    const res = await request({
      url: '/games/selectCategory',
      method: 'post',
      params: { categoryName: category },
    });
    if (res.data.code === 200) {
      filteredGames.value = res.data.data || [];
      activeCategory.value = category;
    } else {
      ElMessage.error('筛选失败');
    }
  } catch (err) {
    console.error('筛选失败:', err.response?.data || err);
    ElMessage.error('筛选失败，请检查网络');
  }
};


// 查看游戏详情
const viewGameDetails = (gameId) => {
  router.push(`/game/${gameId}`);
};

// 切换账号
const switchUser = (username) => {
  store.switchPageUser(pageKey.value, username);
  getUserInfo();
  ElMessage.success(`已切换到用户: ${username}`);
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  list();
};

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString();
};

// 处理折叠面板变化
const handleChange = (val) => {
  console.log('折叠面板变化:', val);
};

// 收藏/取消收藏游戏 - 占位符
const toggleFavorite = (gameId) => {
  console.log('Toggle favorite for game:', gameId);
  // 实际实现需要后端接口支持
};
</script>
  
<style scoped>
/* 全局样式 */
.common-layout {
  min-height: 100vh;
  background-color: #f0f4f8;
}

/* 头部样式 */
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #2c3e50;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  height: 60px;
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 1000;
}

.logo {
  display: flex;
  align-items: center;
}

.logo img {
  height: 35px;
  margin-right: 10px;
}

.yz {
  font-size: 16px;
  font-weight: bold;
  color: #ffffff;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-section {
  margin-right: 20px;
}

.search-input {
  border-radius: 20px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  width: 300px;
  max-width: 300px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 35px;
  height: 35px;
  border: 2px solid #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-dropdown-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  background: transparent;
  border: none;
  font-weight: 500;
  color: #ffffff;
}

.dropdown-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  width: 100%;
  justify-content: flex-start;
  padding: 8px 10px;
  border: none;
  color: #2c3e50;
  background-color: #ffffff;
}

/* 主内容区样式 */
.el-main {
  padding: 70px 20px 20px;
  min-height: calc(100vh - 60px);
}

/* 公告区样式 */
.announcement-section {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #ffffff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  max-height: 200px;
  overflow-y: auto;
}

.custom-collapse {
  border: none;
}

.announcement-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.announcement-title {
  font-weight: 500;
  font-size: 14px;
}

.announcement-date {
  font-size: 12px;
  color: #999;
  margin-left: auto;
}

.announcement-content {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-top: 10px;
  line-height: 1.5;
  font-size: 14px;
}

/* 区域标题样式 */
.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.section-icon {
  font-size: 20px;
  color: #409eff;
  margin-right: 10px;
}

.section-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

/* 分类导航样式 */
.category-section {
  margin-bottom: 20px;
  border-radius: 8px;
  background-color: #ffffff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  padding: 15px;
}

.category-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 5px 0;
}

.category-bar .el-button {
  border-radius: 20px;
  padding: 8px 15px;
  background-color: #f0f4f8;
  border: 1px solid #409eff;
  color: #2c3e50;
  transition: all 0.3s;
}

.active-category {
  background-color: #409eff;
  color: #ffffff;
  transform: scale(1.05);
  font-weight: bold;
}

/* 游戏列表样式 */
.games-section {
  border-radius: 8px;
  background-color: #ffffff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  padding: 20px;
  flex-grow: 1;
}

.game-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 30px;
  margin-top: 20px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

/* 页脚样式 */
.footer {
  background-color: #2c3e50;
  color: white;
  padding: 30px 0;
}

.footer-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.footer-logo {
  display: flex;
  align-items: center;
  gap: 10px;
}

.footer-logo img {
  height: 40px;
}

.footer-links {
  display: flex;
  gap: 20px;
}

.footer-links button {
  color: navy;
  text-decoration: none;
  transition: color 0.3s;
}

.footer-links button:hover {
  color: black;
}

.footer-copyright {
  font-size: 12px;
  color: #aaa;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .header-container {
    padding: 0 15px;
  }

  .logo img {
    height: 30px;
  }

  .yz {
    font-size: 14px;
  }

  .search-input {
    width: 200px;
  }

  .avatar {
    width: 30px;
    height: 30px;
  }

  .user-dropdown-btn {
    font-size: 14px;
  }

  .el-main {
    padding: 70px 15px 15px;
  }

  .announcement-section {
    max-height: 220px;
  }

  .section-title {
    font-size: 16px;
  }

  .section-icon {
    font-size: 18px;
  }

  .category-section {
    padding: 10px;
  }

  .category-bar .el-button {
    padding: 7px 12px;
    font-size: 14px;
  }

  .games-section {
    padding: 15px;
  }

  .game-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 25px;
  }

  .footer {
    padding: 20px 0;
  }

  .footer-logo img {
    height: 35px;
  }

  .footer-logo span {
    font-size: 14px;
  }

  .el-dialog {
    width: 80%;
  }
}

@media (max-width: 768px) {
  .header-container {
    height: 100px;
    flex-direction: column;
    justify-content: center;
    padding: 10px;
    gap: 10px;
  }

  .logo {
    margin-bottom: 0;
  }

  .logo img {
    height: 28px;
  }

  .yz {
    font-size: 14px;
  }

  .header-right {
    flex-direction: column;
    width: 100%;
    gap: 10px;
  }

  .search-section {
    width: 100%;
    margin-right: 0;
  }

  .search-input {
    width: 100%;
    max-width: 100%;
  }

  .search-input .el-input__inner {
    font-size: 16px;
    padding: 8px 12px;
  }

  .search-input .el-button {
    padding: 8px 15px;
    font-size: 14px;
  }

  .user-info {
    justify-content: center;
  }

  .avatar {
    width: 32px;
    height: 32px;
  }

  .user-dropdown-btn {
    padding: 8px 15px;
    font-size: 14px;
  }

  .dropdown-btn {
    font-size: 14px;
    padding: 8px 12px;
  }

  .el-main {
    padding: 110px 10px 10px;
    min-height: calc(100vh - 100px);
  }

  .announcement-section {
    max-height: 250px;
  }

  .announcement-title {
    font-size: 18px;
  }

  .announcement-date {
    font-size: 16px;
  }

  .announcement-content {
    font-size: 18px;
    padding: 12px;
    line-height: 1.6;
  }

  .section-title {
    font-size: 16px;
  }

  .section-icon {
    font-size: 16px;
  }

  .category-section {
    padding: 10px 5px;
  }

  .category-bar {
    flex-wrap: nowrap;
    overflow-x: auto;
    gap: 15px;
    padding: 10px 5px;
    white-space: nowrap;
  }

  .category-bar .el-button {
    padding: 10px 20px;
    font-size: 16px;
    min-width: 100px;
  }

  .category-bar::-webkit-scrollbar {
    height: 8px;
  }

  .category-bar::-webkit-scrollbar-thumb {
    background: #409eff;
    border-radius: 10px;
  }

  .games-section {
    padding: 10px;
  }

  .game-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
  }

  .pagination-container .el-pagination {
    font-size: 16px;
  }

  .pagination-container .el-pagination .el-pager li {
    min-width: 30px;
    height: 30px;
    line-height: 30px;
    font-size: 16px;
  }

  .pagination-container .el-pagination__jump {
    display: none;
  }

  .footer {
    padding: 15px 0;
  }

  .footer-content {
    gap: 15px;
  }

  .footer-logo img {
    height: 30px;
  }

  .footer-logo span {
    font-size: 14px;
  }

  .footer-links button {
    font-size: 14px;
    padding: 8px 15px;
  }

  .footer-copyright {
    font-size: 12px;
  }

  .el-dialog {
    width: 90%;
    padding: 15px;
  }

  .el-dialog__body p {
    font-size: 16px;
    line-height: 1.6;
  }

  .el-dialog__title {
    font-size: 18px;
  }

  .dialog-footer .el-button {
    font-size: 16px;
    padding: 10px 20px;
  }
}

@media (max-width: 480px) {
  .header-container {
    height: 90px;
  }

  .logo img {
    height: 25px;
  }

  .yz {
    font-size: 12px;
  }

  .search-input .el-input__inner {
    font-size: 14px;
  }

  .search-input .el-button {
    padding: 6px 12px;
    font-size: 12px;
  }

  .avatar {
    width: 28px;
    height: 28px;
  }

  .user-dropdown-btn {
    font-size: 12px;
  }

  .dropdown-btn {
    font-size: 12px;
    padding: 6px 10px;
  }

  .el-main {
    padding: 100px 8px 8px;
    min-height: calc(100vh - 90px);
  }

  .announcement-section {
    max-height: 200px;
  }

  .announcement-title {
    font-size: 16px;
  }

  .announcement-date {
    font-size: 14px;
  }

  .announcement-content {
    font-size: 16px;
    padding: 10px;
  }

  .section-title {
    font-size: 14px;
  }

  .section-icon {
    font-size: 14px;
  }

  .category-bar .el-button {
    padding: 8px 15px;
    font-size: 14px;
    min-width: 80px;
  }

  .games-section {
    padding: 8px;
  }

  .game-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 15px;
  }

  .pagination-container .el-pagination {
    font-size: 14px;
  }

  .pagination-container .el-pagination .el-pager li {
    min-width: 25px;
    height: 25px;
    line-height: 25px;
    font-size: 14px;
  }

  .footer-logo img {
    height: 25px;
  }

  .footer-logo span {
    font-size: 12px;
  }

  .footer-links button {
    font-size: 12px;
    padding: 6px 12px;
  }

  .footer-copyright {
    font-size: 10px;
  }

  .el-dialog {
    width: 95%;
    padding: 10px;
  }

  .el-dialog__body p {
    font-size: 14px;
  }

  .el-dialog__title {
    font-size: 16px;
  }

  .dialog-footer .el-button {
    font-size: 14px;
    padding: 8px 15px;
  }
}
</style>